package com.sml.aop.cat;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author linlx
 * @Date 2021/8/26 11:29
 * @Description
 **/
@Aspect
public class CatUrlAspect {

  @Around(value = "@annotation(CatUrlAnnotation)")
  public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
    ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes();
    HttpServletRequest request = sra.getRequest();
    String requestURI = request.getRequestURI();
    Transaction t = Cat.newTransaction("URL", requestURI);

    StringBuilder sb = new StringBuilder(1024);
    String ip;
    String ipForwarded = request.getHeader("x-forwarded-for");
    if (ipForwarded == null) {
      ip = request.getRemoteAddr();
    } else {
      ip = ipForwarded;
    }
    sb.append("IPS=").append(ip);
    sb.append("&VirtualIP=").append(request.getRemoteAddr());
    sb.append("&Server=").append(request.getServerName());
    sb.append("&Referer=").append(request.getHeader("referer"));
    sb.append("&Agent=").append(request.getHeader("user-agent"));
    Cat.logEvent("URL", "URL" + ".Server", Message.SUCCESS, sb.toString());
    try {
      Object res = pjp.proceed();
      t.setSuccessStatus();
      return res;
    } catch (Throwable e) {
      t.setStatus(e);
      Cat.logError(e);
      throw e;
    } finally {
      t.complete();
    }
  }

}
